<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/10/30 0030
 * Time: 下午 1:02
 */

namespace app\controller;


use app\BaseController;
use app\model\Access;
use app\model\Profile;
use app\model\Role;
use app\model\Users;
use think\facade\Db;
class Models extends BaseController
{

    function index(){

        //关联查询
        //$ret = Users::find(4);
        //会走__get拦截器查询
       // $ret->profile->save(['hobby'=>'喜欢偷东西']);
        //不走拦截器直接调用
       // $ret->profile()->save(['hobby'=>'喜欢偷鸡','gender'=>'人妖']);

        //return json($ret->profile);
        //$user = Users::hasWhere("profile")->where("id",4)->find();
        //return json($user);

        //$profile = Profile::find(4);
        //$ret =  $profile->users;
        //echo Db::getLastSql();
        //return json($profile->users);

        $ret = Users::find(4);
        return json($ret->profile);
    }

    function load(){

        //会查找多次
//        $list = Users::select([4,5,6]);
//
//        foreach ($list as $user){
//
//            dump($user->profile->toArray());
//        }

        //关联预载入，减少查询语句
        //$list = Users::with(["profile","book"])->select([4,5,6]);
        $list = Users::select([4,5,6]);
        $list->load(["profile","book"]);



        foreach ($list as $user){

            //dump($user->profile->toArray());
            dump($user->profile."-");
            dump($user->book."-");
        }
    }

    function count(){
        //关联统计
        //$list = Users::withCount(["profile"])->select([4,5,6]);
//        $list = Users::withSum(["profile"],"id")->select([4,5,6]);
//
//        foreach ($list as $user){
//            //dump($user->profile_count);
//            dump($user->profile_sum);
//            //dump($user->profile->toArray());
//        }

        //$list = Users::with(["profile","book"])->select([4,5,6]);
        $list = Users::with(["profile"])->select([4,5,6]);

        //return json($list->hidden(["name","profile.gender"]));
        return json($list->append(["book"]));

    }

    function many(){

        //$user = Users::find(4);
        //return json($user->roles);

        $user = Users::find(4);
        $role = Access::where("uid",$user->id)->find();
        $privileged = Role::where("id",$role->role_id)->find();

        print_r($user->name);

        print_r($privileged->type);
    }



}